package com.zoe.onelink.guide.provider;

import cn.hutool.core.thread.ThreadUtil;
import com.zoe.onelink.common.entity.ResultVO;
import com.zoe.onelink.common.enumeration.ExceptionCode;
import com.zoe.onelink.common.exception.ApiException;
import com.zoe.onelink.common.model.IResult;
import com.zoe.onelink.core.exception.guide.OnelinkExceptionGuideProvider;
import com.zoe.onelink.guide.loader.OnelinkGuideLoader;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-09-18
 */
@Slf4j
@RequiredArgsConstructor
public class OnelinkApiExceptionGuideProvider implements OnelinkExceptionGuideProvider, InitializingBean {

    private final Map<String, String> guideMap = new HashMap<>();
    private final Map<String, OnelinkGuideLoader> onelinkGuideLoaderMap;

    @Override
    public boolean supports(Throwable ex, IResult<?> result) {
        return result instanceof ResultVO;
    }

    @Override
    public String getGuide(Throwable ex, IResult<?> result) {
        if (ex instanceof ApiException) {
            ExceptionCode exceptionCode = ((ApiException) ex).getExceptionCode();
            return this.guideMap.get(exceptionCode.getMessageKey());
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() {
        ThreadUtil.execute(() -> {
            if (this.onelinkGuideLoaderMap == null || this.onelinkGuideLoaderMap.isEmpty()) {
                return;
            }
            for (Map.Entry<String, OnelinkGuideLoader> entry : this.onelinkGuideLoaderMap.entrySet()) {
                try {
                    OnelinkGuideLoader loader = entry.getValue();
                    Map<String, String> subGuideMap = loader.loadGuide();
                    this.guideMap.putAll(subGuideMap);
                } catch (Exception e) {
                    log.error("[异常指南模块] [{}] 加载数据失败!", entry.getKey(), e);
                }
            }
            log.info("[异常指南模块] 共找到 {} 条异常指南信息", this.guideMap.size());

        });
    }

}
